package socket;

import java.io.*;
import java.net.InetAddress;
import java.net.Socket;

/**
 * @author DCSGO
 * @version 1.0
 * 客户端
 * 使用字符流向服务端发送"你好，服务端！"
 * 并接收服务端回传的消息
 */
public class SocketTCP03Client {
    public static void main(String[] args) throws IOException {
        int port = 9999;
        Socket socket = new Socket(InetAddress.getLocalHost(), port);
        //Socket socket = new Socket(InetAddress.getByName("47.113.198.9"), port);

        System.out.println("已连接到服务端!");
        BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
        System.out.println("正在向服务端发送消息...");
        bufferedWriter.write("你好，服务端！");
        //字符流的读取常用 readLine 为与之对应 故加上 newLine 防止出现 Bug
        bufferedWriter.newLine();
        bufferedWriter.flush();//必须刷新才能真正写入字符
        socket.shutdownOutput();//设置写入结束标记

        System.out.println("消息发送完毕!");
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        System.out.println("正在接收服务端回传的消息...");
        String line;
        while ((line = bufferedReader.readLine()) != null) {
            System.out.println(line);
        }
        System.out.println("服务端回传的消息已接收!");

        bufferedWriter.close();
        bufferedReader.close();
        socket.close();
        System.out.println("程序已结束...");

        /*
         * 已连接到服务端!
         * 正在向服务端发送消息...
         * 消息发送完毕!
         * 正在接收服务端回传的消息...
         * 你好，客户端！
         * 服务端回传的消息已接收!
         * 程序已结束...
         *
         * 进程已结束，退出代码为 0
         */
    }
}
